package com.imooc.mall.common;

import com.imooc.mall.exception.ImoocMallExceptionEnum;

/**
 * 通用返回对象
 */
public class ApiRestResponse<T> {
    private Integer status;
    private String msg;
    private T data;

    private static final Integer SUCCESS_CODE = 0;
    private static final Integer ERROR_CODE = 500;

    private static final String SUCCESS_MSG = "SUCCESS";
    private static final String ERROR_MSG = "ERROR";
    private static final String UNAUTHORIZED_MSG = "UNAUTHORIZED";


    public ApiRestResponse(Integer status, String msg, T data) {
        setStatus(status);
        setMsg(msg);
        setData(data);
    }

    public ApiRestResponse(Integer status, String msg) {
        setStatus(status);
        setMsg(msg);
    }

    public ApiRestResponse() {
        this(SUCCESS_CODE, SUCCESS_MSG);
    }

    public static <T> ApiRestResponse<T> success() {
        return new ApiRestResponse<>();
    }

    public static <T> ApiRestResponse<T> success(T data) {
        return new ApiRestResponse<>(SUCCESS_CODE, SUCCESS_MSG, data);
    }

    public static <T> ApiRestResponse<T> error(Integer status, String msg) {
        return new ApiRestResponse<>(status, msg);
    }

    public static <T> ApiRestResponse<T> error(ImoocMallExceptionEnum exceptionEnum) {
        return new ApiRestResponse<>(exceptionEnum.getCode(), exceptionEnum.getMessage());
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        // 简洁实现，使用字符串拼接生成JSON格式
        StringBuilder json = new StringBuilder();
        json.append("{");
        json.append("\"status\":").append(status).append(",");
        json.append("\"msg\":\"").append(msg != null ? unicodeEscape(msg) : "").append("\",");
        json.append("\"data\":");
        
        // 处理data字段
        if (data == null) {
            json.append("null");
        } else {
            String dataStr = data.toString();
            // 判断data是否已经是JSON格式（以{开头或以[开头）
            if ((dataStr.startsWith("{") && dataStr.endsWith("}")) || 
                (dataStr.startsWith("[") && dataStr.endsWith("]"))) {
                json.append(dataStr);
            } else {
                // 不是JSON格式，作为字符串处理
                json.append("\"").append(unicodeEscape(dataStr)).append("\"");
            }
        }
        
        json.append("}");
        return json.toString();
    }
    
    /**
     * 将字符串转换为Unicode转义序列
     * 这确保所有中文和特殊字符都能正确显示，无论环境编码如何
     */
    private String unicodeEscape(String input) {
        if (input == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c < 128) {
                // ASCII字符直接处理
                switch (c) {
                    case '"': sb.append("\\\""); break;
                    case '\\': sb.append("\\\\"); break;
                    case '\b': sb.append("\\b"); break;
                    case '\f': sb.append("\\f"); break;
                    case '\n': sb.append("\\n"); break;
                    case '\r': sb.append("\\r"); break;
                    case '\t': sb.append("\\t"); break;
                    default: sb.append(c);
                }
            } else {
                // 非ASCII字符（如中文）使用Unicode转义
                sb.append(String.format("\\u%04x", (int)c));
            }
        }
        return sb.toString();
    }
}
